package com.fzk.router;

import com.fzk.log.Logger;
import com.fzk.server.HttpResponseUtil;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;

import java.util.List;
import java.util.Map;

/**
 * 将一个请求映射到某个处理器
 *
 * @author fzk
 * @datetime 2023-04-11 00:02:38
 */

public class HandlerMapping {
    public final MatchRule rule;
    public final ApiHandler apiHandler;

    public HandlerMapping(String path, List<HttpMethod> methods, ApiHandler apiHandler) {
        this.rule = MatchRule.of(path, methods);
        this.apiHandler = apiHandler;
    }

    public boolean match(String path, HttpMethod method) {
        return rule.match(path, method);
    }

    public final void execute(MyCtx ctx, FullHttpRequest request, Map<String, List<String>> params) {
        try {
            apiHandler.handle(ctx, request, params);
        } catch (Exception e) {
            e.printStackTrace();
            Logger.error(e.getMessage());
            HttpResponseUtil.sendError(ctx.getChannelCtx(), HttpUtil.isKeepAlive(request), HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
    }
}